package com.yehui.jdk.jdk11;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

/**
 * https://mkyong.com/java/java-11-httpclient-examples/
 *
 * @author 业徽
 * @date 2021/8/23
 */
public class HttpClientDemo {

    public static void main(String[] args) throws IOException, InterruptedException {
        final HttpClient httpClient = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .version(HttpClient.Version.HTTP_1_1)
                .build();

        final HttpRequest httpRequest = HttpRequest.newBuilder()
                .GET()
                .uri(URI.create("https://www.baidu.com"))
                .setHeader("appCode", "haha")
                .build();
        final HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());

        final HttpHeaders headers = httpResponse.headers();
        headers.map().forEach((k, v) -> {
            System.out.printf("header key: %s, value: %s\n", k, v);
        });

        System.out.println("statusCode: " + httpResponse.statusCode());
        System.out.println("body: " + httpResponse.body());
    }

}
